package com.comtop.topcloud.device.config;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.mqttv5.client.*;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@Slf4j
public class MqttConfig {

    @Value("${mqtt.broker-url}")
    private String brokerUrl;

    @Value("${mqtt.client-id}")
    private String clientId;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.connection-timeout}")
    private int connectionTimeout;

    @Value("${mqtt.keep-alive-interval}")
    private int keepAliveInterval;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient client = new MqttClient(brokerUrl, clientId);

        // 配置连接选项
        MqttConnectionOptions options = new MqttConnectionOptions();
        options.setUserName(username);
        options.setPassword(password.getBytes());
        options.setAutomaticReconnect(true);  // 启用自动重连
        options.setCleanStart(true);          // 清理会话
        options.setConnectionTimeout(connectionTimeout);     // 连接超时时间（秒）
        options.setKeepAliveInterval(keepAliveInterval);     // 心跳间隔（秒）

        // 设置回调
        client.setCallback(new MqttCallback() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
            }

            @Override
            public void authPacketArrived(int i, MqttProperties mqttProperties) {

            }



            @Override
            public void disconnected(MqttDisconnectResponse mqttDisconnectResponse) {
            }

            @Override
            public void mqttErrorOccurred(MqttException e) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // 处理接收到的消息
            }

            @Override
            public void deliveryComplete(IMqttToken token) {

            }
        });

        // 连接到 MQTT Broker
        try {
            client.connect(options);
        } catch (MqttException e) {
            log.error("MQTT 连接失败: {}", e.getMessage());
            throw e;
        }

        return client;
    }



}
